<template>
	<Layout class="p-5 bg-white">
		<Form :label-width="80">
			
			<FormItem class="" label="产品名称">
				<Input v-model="product.name" placeholder="请输入产品名称"></Input>
			</FormItem>
			
			 <!-- <Option v-for="item in cardStatus"
			                  :value="item.val"
			                  :key="item.val">{{ item.name }}</Option>
							  -->
			<FormItem v-if="this.change ==0" class="w-50"  label="产品分类">
				<Input  v-for="item in this.categoryArr" :value="item" disabled="" >
					
				</Input>
				<Button  class="mt-2 "  style="float: right;" type="error" @click="changeType()" >重置分类</Button>
			</FormItem>
			
			<FormItem v-if="this.change==1" class=""   label="更改产品分类">
				<Select  @on-change="loadCategorys(item.categoryId, item.value)" v-for="(item, index) in this.categorysArrays" :key="index" v-model="item.value"  >
					<Option v-for="(category, jndex) in item.source" :key="jndex" :value="category.categoryId">{{category.name}}</Option>
				</Select>
				<Button  class="mt-2 "  style="float: right;" type="error" @click="changeType()" >重置分类</Button>
			</FormItem>
			
			<FormItem class="" label="产品状态">
			    <i-switch v-model="product.statu"></i-switch>
			   </FormItem>
			
			<FormItem class="" label="产品价格">
				<Input v-model="product.price" @on-keyup="price(product.price)" placeholder="请输入产品价格"></Input>
			</FormItem>
			
			<FormItem class="w-50" label="产品封面">
				<div class="d-flex flex-row">
					
					<label style="line-height: 30px;" class="ivu-btn ivu-btn-default ml-1" for="cover">选择文件</label>
					<input @change="fileChange($event,coverFile)" id="cover" style="display: none;" type="file"></input>
				</div>
				
				<div class="d-flex flex-row mt-2" v-if="!coverFile.url">
					<img  class="w-50" :src="'https://'+image.url"  />
				</div>
				<div class="d-flex flex-row mt-2" v-if="coverFile.url">
					<img  class="w-50" :src="coverFile.url"  />
				</div>
			

				</div>
			</FormItem>
			<FormItem class="w-50" label="产品详情图片">
				<div class="d-flex flex-row">
					<Button @click="addImg" type="info">添加图片</Button>
				</div>
				
				
				<div class=" mt-2">
					<span class="m-2 d-inline-block w-25" v-for="(img, index) in detailFiles" :key="index">
						<label class="w-100" :for="'detail'+index">
							<img v-if="img.url" class="w-100" :src="img.url" />
							<span v-else >选择文件</span>
						</label>
						<input @change="fileDetailChange($event, img)" :id="'detail'+index" style="display: none;" type="file"></input>
						<Button :id="index" @click="deleteNewImg(index)" type="error">删除</Button>
					</span>
				</div>
				
				<div class=" mt-2">
					<span class="m-2 d-inline-block w-25" v-for="(img, index) in urlS" :key="index">
						<label class="w-100" :for="'detail'+index">
							<img v-if="img.url" class="w-100" :src="'https://'+img.url" />
							<span v-else >选择文件</span>
						</label>
						<input @change="fileDetailChange($event, img)" :id="'detail'+index" style="display: none;" type="file"></input>
						<Button :id="index" @click="deleteImg(index)" type="error">删除</Button>
					</span>
				</div>
			</FormItem>
			<Row class="p-1">
				<Col span="24">
					<FormItem class=""  label="产品图文内容">
						<div  style="display: block; position: relative; z-index: 0;" id="editor">
							
						</div>
					</FormItem>
				</Col>
			</Row>
			<FormItem class="text-right">
				<Button @click="submit" type="primary">修改并提交</Button>
				<Button @click="cancel" class="ml-2">取消</Button>
			</FormItem> 
		</Form>
	</Layout>
</template>

<script>
	import E from "wangeditor";
	
	export default {
		
		data() {
			return {
				product:{
					productId: "",
					name: "",
					price: "",
					coverImageId:"",
					categorys:"",
					contant:"",
					statu:"",
				},
				image: {
					imgId: "",
					url: "",
					statu: "",
					dFlg: ""
				},
				category_detail: {
					categoryId: "",
					detailId: "",
					contant: "",
				},
				coverFile: {
					name: "",
					file: undefined,
					url:""
				},
				detailFiles: [
					
				],
				categorysArrays: [
					
				],
				urlS:"",
				categoryArr:[
					
				],
				categorys:[
					
				],
				change:"0",

				

			}
		},
		methods: {
			price(){
			         if(this.product.price == 0){
			           this.product.price=""
			         }else{
			           this.product.price=this.product.price.replace(/\D/g,'')
			         }
			     
			       },
			getColumnValuesFromJSONArr: function (jsonArr, attrName) {
			  const jsonStr = JSON.stringify(jsonArr);
			  let attrValArr = [];
			  const regExp = new RegExp('"' + attrName + '":"■(.*?)■"', 'mg');
			  while (regExp.test(jsonStr)) {
			      attrValArr.push(RegExp.$1);
			  }
			  return attrValArr;
			},
			

			changeType: function(i){
				
				this.categorys = []
				this.categorysArrays = []
				this.loadCategorys(null, 0);
				this.change = 1
				
			},
			loadCategorys: function(event, categoryId) {
				
				let targetIndex = undefined;
				for (let index = 0; index < this.categorysArrays.length; index++) {
					let targetCategorys = this.categorysArrays[index];
					if (event === targetCategorys.categoryId) {
						targetIndex = index;
						break;
					}
				}
				
				targetIndex = targetIndex + 1;
				
				if (targetIndex !== undefined) {
					this.categorysArrays.splice(targetIndex, this.categorysArrays.length - targetIndex);
					
					console.log(this.categorysArrays);
				}
				
				if (categoryId !== null && categoryId !== undefined && categoryId !== "") {
					this.http.get({
						url: "/product/category/info",
						param: {
							categoryId
						}
					}).then(res => {
						console.log(res);
						
						let categorysSource = {
							categoryId,
							value: "",
							source: res.category.subCategory
						};
						
						this.categorysArrays.push(categorysSource);
						
						if(categoryId !== 0){
							let category = {
								categoryId:"■"+categoryId+"■",
								name:"■"+res.category.name+"■"
							}
							console.log(this.categorys)
							this.categorys.push(category)
						}
					});
				}
				
				
				
			},
			
			addImg: function() {
				
				
				this.detailFiles.push({
					
					
					name: this.detailFiles.length,
					file: undefined,
					url: "",
				});
			},
			fileDetailChange: function(e, imgItem) {
				imgItem.file = e.target.files[0];
				imgItem.name = imgItem.file.name;
				
				let reader = new FileReader();
				reader.onloadend = function() {
					imgItem.url = this.result;
				}
				reader.readAsDataURL(imgItem.file);
				
				imgItem.onProgress = this.onProgress;
			},
			deleteImg: function(index) {
				console.log(index);
				this.urlS.splice(index, 1);
				console.log(this.urlS);
			},
			deleteNewImg: function(index) {
				this.detailFiles.splice(index, 1);
				console.log(this.detailFiles);
			},
			changeP: function(selectedPermissionId) {
				if (selectedPermissionId === 0) {
					this.permission.path = "";
				}
			},
			fileChange: function(e,imgItem) {
				
				
				imgItem.file = e.target.files[0];
				imgItem.name = imgItem.file.name;
				
				let reader = new FileReader();
				reader.onloadend = function() {
					imgItem.url = this.result;
					this.url = this.result;
				}
				reader.readAsDataURL(imgItem.file);
				imgItem.onProgress = this.onProgress;
				console.log(this.url);
			},
			submit: function() {
				
				let self = this;
				
				if (this.product.name.length === 0) {
					this.message.error("请输入产品名称");
					return;
				}
				if (this.product.categorys.length === 0) {
					this.message.error("请选择产品分类");
					return;
				}
				if (this.product.statu.length === 0) {
					this.message.error("请选择产品状态");
					return;
				}
				if (this.product.price.length === 0) {
					this.message.error("请输入产品价格");
					return;
				}
				if (this.product.price < 0) {
					this.message.error("产品价格不能为负数");
					return;
				}
				// if (this.product.pId !== 0) {
				// 	if (this.permission.path.length === 0) {
				// 		this.message.error("请输入权限路径");
				// 		return;
				// 	}
				// }
				
				// delete self.permission.cu;
				// delete self.permission.ct;
				// delete self.permission.uu;
				// delete self.permission.ut;
				if(self.coverFile.url == null || self.coverFile.url == "" || self.coverFile.url == undefined){
					self.http.put({
						url: "/product/product/info",
						param: {
							productId:self.product.productId,
							name: self.product.name,
							price: self.product.price,
							categorys:JSON.stringify(self.categorys),
							contant: self.editor.txt.html(),
							statu: self.product.statu,
							url:self.image.url
						}
					}).then(data => {
						self.message.info("修改成功");
						self.$tabs.close();
					});
					
				}else{
					self.common.submitFile(self.coverFile).then(function(res) {
						self.coverFile.url = res.Location;
						console.log(self.coverFile.url)
					self.http.put({
						url: "/product/product/info",
						param: {
							productId:self.product.productId,
							name: self.product.name,
							price: self.product.price,
							categorys:self.product.categorys,
							contant: self.editor.txt.html(),
							statu: self.product.statu,
							url:self.coverFile.url
						}
					}).then(data => {
						self.message.info("修改成功");
						self.$tabs.close();
					});
					}).catch(function(err) {
						console.log(err)
						self.message.error("封面文件上传失败，取消修改产品。");
					});
					
				}
				
				
				
				
			},
			cancel: function() {
				this.$tabs.close();
			},
			init: function() {
				
				let self = this;
				
				this.http.get({
					
					url: "/product/info",
					param: {
						productId:self.product.productId,
						name: self.product.name,
						price:self.product.price,
						coverImageId:self.product.coverImageId,
						categorys:self.product.categorys,
						contant:self.product.contant,
						statu:self.product.statu,
						url:self.coverFile.url,
						urlS:self.detailFiles.url
					}
				}).then(data => {
					self.product.productId = data.product.productId,
					self.product.name = data.product.name
					self.product.categorys = data.product.categorys,
					self.product.statu = data.product.statu,
					self.product.price = data.product.price,
					self.product.coverImageId = data.product.coverImageId,
					self.editor.txt.html(data.product.contant),
					self.image.url = data.coverImage.url,
					self.urlS = data.image,
					self.categoryArr = JSON.parse(data.product.categorys),

					self.loadCategorys(null, 0);
					console.log(self.product.categorys)
					
					
					self.categoryArr =(self.getColumnValuesFromJSONArr( self.categoryArr,"name"))
					console.log(self.categoryArr)
				});
				
				
				
				// this.http.get({
				// 	url: "/product/info"
				// }).then(data => {
				// 	self.allPermissions.push({
				// 		permissionId: 0,
				// 		name: "顶级菜单"
				// 	});
				// 	for (let index in data) {
				// 		let permission = {};
				// 		permission.permissionId = data[index].permissionId;
				// 		permission.name = data[index].name;
				// 		self.allPermissions.push(permission);
				// 	}
				// 	console.log(self.allPermissions);
				// }).then(() => {
					
				// 	self.http.get({
				// 		url: "/permission/info",
				// 		param: {
				// 			permissionId: self.permission.permissionId
				// 		}
				// 	}).then(data => {
				// 		console.log(data);
				// 		self.permission = data;
				// 	});
					
					
				}
			},
			mounted() {
				this.editor = new E("#editor");
				
				let self = this;
				this.editor.config.customUploadImg = this.common.editorUploadFile;
				this.editor.create();
			},
			created: function(){
				this.product.productId = this.$route.query.productId;
				this.init();
				
			}
		}
		
	
</script>